package com.wilmer.question.controller;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.wilmer.common.exception.ServiceException;
import com.wilmer.common.utils.StringUtils;
import com.wilmer.options.domain.YwOptions;
import com.wilmer.options.service.IYwOptionsService;
import com.wilmer.question.domain.YwQuestionVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wilmer.common.annotation.Log;
import com.wilmer.common.core.controller.BaseController;
import com.wilmer.common.core.domain.AjaxResult;
import com.wilmer.common.enums.BusinessType;
import com.wilmer.question.domain.YwQuestion;
import com.wilmer.question.service.IYwQuestionService;
//import com.wilmer.common.utils.poi.ExcelUtil;
import com.wilmer.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 题库题干Controller
 *
 * @author zl
 * @date 2024-04-16
 */
@RestController
@RequestMapping("/question/question")
public class YwQuestionController extends BaseController {
    @Autowired
    private IYwQuestionService ywQuestionService;
    @Autowired
    private IYwOptionsService ywOptionsService;


    @PreAuthorize("@ss.hasPermi('question:question:list')")
    @GetMapping({"/list"})
    public TableDataInfo list(YwQuestion ywQuestion) {
        this.startPage();
        List<YwQuestion> list = this.ywQuestionService.selectYwQuestionList(ywQuestion);
        return this.getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('question:question:export')")
    @Log(
            title = "题库题干",
            businessType = BusinessType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, YwQuestion ywQuestion) {
        List<YwQuestion> list = this.ywQuestionService.selectYwQuestionList(ywQuestion);
        com.wilmer.common.utils.poi.ExcelUtil<YwQuestion> util = new com.wilmer.common.utils.poi.ExcelUtil(YwQuestion.class);
        util.exportExcel(response, list, "题库题干数据");
    }

    @PostMapping({"/importTemplate"})
    public void importTemplate(HttpServletResponse response) {
        com.wilmer.common.utils.poi.ExcelUtil<YwQuestionVO> util = new com.wilmer.common.utils.poi.ExcelUtil(YwQuestionVO.class);
        util.importTemplateExcel(response, "题库数据");
    }

    @PreAuthorize("@ss.hasPermi('question:question:import')")
    @PostMapping({"/importData"})
    public AjaxResult importData(MultipartFile file, boolean updateSupport, Long courseId) throws Exception {
        InputStream in = file.getInputStream();
        ExcelReader excelReader = cn.hutool.poi.excel.ExcelUtil.getReader(in);
        List<List<Object>> list = excelReader.read(2);
        if (!StringUtils.isNull(list) && list.size() != 0) {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();
            String one = "";
            Long questionId = 0L;
            Iterator var13 = list.iterator();

            while(var13.hasNext()) {
                List<Object> row = (List)var13.next();
                YwQuestion ywQuestion = new YwQuestion();
                ywQuestion.setContent(row.get(0).toString());
                ywQuestion.setType(row.get(1).toString());
                ywQuestion.setDifficultyLevel(row.get(2).toString());
                BigDecimal numberBD = new BigDecimal(row.get(3).toString());
                ywQuestion.setScore(numberBD);
                ywQuestion.setCourseId(courseId);
                YwOptions ywOptions;
                if (one.equals(row.get(0).toString())) {
                    ywOptions = new YwOptions();
                    ywOptions.setQuestionId(questionId);
                    ywOptions.setContent(row.get(4).toString());
                    ywOptions.setIsCorrect(row.get(5).toString());
                    ywOptions.setOptionOrder(Integer.valueOf(row.get(6).toString()));
                    this.ywOptionsService.insertYwOptions(ywOptions);
                } else {
                    try {
                        one = row.get(0).toString();
                        this.ywQuestionService.insertYwQuestion(ywQuestion);
                        questionId = ywQuestion.getQuestionId();
                        ywOptions = new YwOptions();
                        ywOptions.setQuestionId(questionId);
                        ywOptions.setContent(row.get(4).toString());
                        ywOptions.setIsCorrect(row.get(5).toString());
                        ywOptions.setOptionOrder(Integer.valueOf(row.get(6).toString()));
                        this.ywOptionsService.insertYwOptions(ywOptions);
                        ++successNum;
                        successMsg.append("<br/>" + successNum + "、题描述 " + ywQuestion.getContent() + " 导入成功");
                    } catch (Exception var19) {
                        ++failureNum;
                        String msg = "<br/>" + failureNum + "、题描述 " + ywQuestion.getContent() + " 导入失败：";
                        failureMsg.append(msg + var19.getMessage());
                    }
                }
            }

            if (failureNum > 0) {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            } else {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                return this.success(successMsg.toString());
            }
        } else {
            throw new ServiceException("导入题库数据不能为空！");
        }
    }

    @PreAuthorize("@ss.hasPermi('question:question:query')")
    @GetMapping({"/{questionId}"})
    public AjaxResult getInfo(@PathVariable("questionId") Long questionId) {
        return this.success(this.ywQuestionService.selectYwQuestionByQuestionId(questionId));
    }

    @PreAuthorize("@ss.hasPermi('question:question:add')")
    @Log(
            title = "题库题干",
            businessType = BusinessType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody YwQuestion ywQuestion) {
        return this.toAjax(this.ywQuestionService.insertYwQuestion(ywQuestion));
    }

    @PreAuthorize("@ss.hasPermi('question:question:edit')")
    @Log(
            title = "题库题干",
            businessType = BusinessType.UPDATE
    )
    @PutMapping
    public AjaxResult edit(@RequestBody YwQuestion ywQuestion) {
        return this.toAjax(this.ywQuestionService.updateYwQuestion(ywQuestion));
    }

    @PreAuthorize("@ss.hasPermi('question:question:remove')")
    @Log(
            title = "题库题干",
            businessType = BusinessType.DELETE
    )
    @DeleteMapping({"/{questionIds}"})
    public AjaxResult remove(@PathVariable Long[] questionIds) {
        return this.toAjax(this.ywQuestionService.deleteYwQuestionByQuestionIds(questionIds));
    }

//    /**
//     * 查询题库题干列表
//     */
//    @PreAuthorize("@ss.hasPermi('question:question:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(YwQuestion ywQuestion) {
//        startPage();
//        List<YwQuestion> list = ywQuestionService.selectYwQuestionList(ywQuestion);
//        return getDataTable(list);
//    }
//
//    /**
//     * 导出题库题干列表
//     */
//    @PreAuthorize("@ss.hasPermi('question:question:export')")
//    @Log(title = "题库题干", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, YwQuestion ywQuestion) {
//        List<YwQuestion> list = ywQuestionService.selectYwQuestionList(ywQuestion);
//        com.wilmer.common.utils.poi.ExcelUtil<YwQuestion> util = new com.wilmer.common.utils.poi.ExcelUtil<YwQuestion>(YwQuestion.class);
//        util.exportExcel(response, list, "题库题干数据");
//    }
//
//    @PostMapping("/importTemplate")
//    public void importTemplate(HttpServletResponse response) {
//        com.wilmer.common.utils.poi.ExcelUtil<YwQuestionVO> util = new com.wilmer.common.utils.poi.ExcelUtil<YwQuestionVO>(YwQuestionVO.class);
//        util.importTemplateExcel(response, "题库数据");
//    }
//
//    /**
//     * 导入题库
//     */
//    @PreAuthorize("@ss.hasPermi('question:question:import')")
//    @PostMapping("/importData")
//    public AjaxResult importData(MultipartFile file, boolean updateSupport, Long courseId) throws Exception {
//        //文件处理成io流
//        InputStream in = file.getInputStream();
////        //io流给ExcelReader
//        ExcelReader excelReader = ExcelUtil.getReader(in);
//        //忽略第一行头(第一行是中文的情况),直接读取表的内容
//        List<List<Object>> list = excelReader.read(2);
////        ArrayList<YwQuestionVO> list2 = new ArrayList<>();
//        if (StringUtils.isNull(list) || list.size() == 0) {
//            throw new ServiceException("导入题库数据不能为空！");
//        }
//        int successNum = 0;
//        int failureNum = 0;
//        StringBuilder successMsg = new StringBuilder();
//        StringBuilder failureMsg = new StringBuilder();
//        String one = "";
//        Long questionId = 0L;
//        for (List<Object> row : list) {
////            YwQuestionVO ywQuestionVO = new YwQuestionVO();
//            YwQuestion ywQuestion = new YwQuestion();
//            ywQuestion.setContent(row.get(0).toString());
//            ywQuestion.setType(row.get(1).toString());
//            ywQuestion.setDifficultyLevel(row.get(2).toString());
//            BigDecimal numberBD = new BigDecimal(row.get(3).toString());
//            ywQuestion.setScore(numberBD);
//            ywQuestion.setCourseId(courseId);
//            if (one.equals(row.get(0).toString())) {
//                //下一行和上一行一样  只添加答案
//                YwOptions ywOptions = new YwOptions();
//                ywOptions.setQuestionId(questionId);
//                ywOptions.setContent(row.get(4).toString());
//                ywOptions.setIsCorrect(row.get(5).toString());
//                ywOptions.setOptionOrder(Integer.valueOf(row.get(6).toString()));
//                ywOptionsService.insertYwOptions(ywOptions);
//            } else {
//                try {
//                    one = row.get(0).toString();
//                    //添加题和答案
//                    ywQuestionService.insertYwQuestion(ywQuestion);
//                    questionId = ywQuestion.getQuestionId();
//                    YwOptions ywOptions = new YwOptions();
//                    ywOptions.setQuestionId(questionId);
//                    ywOptions.setContent(row.get(4).toString());
//                    ywOptions.setIsCorrect(row.get(5).toString());
//                    ywOptions.setOptionOrder(Integer.valueOf(row.get(6).toString()));
//                    ywOptionsService.insertYwOptions(ywOptions);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、题描述 " + ywQuestion.getContent() + " 导入成功");
//                } catch (Exception e) {
//                    failureNum++;
//                    String msg = "<br/>" + failureNum + "、题描述 " + ywQuestion.getContent() + " 导入失败：";
//                    failureMsg.append(msg + e.getMessage());
//                }
//
//            }
//        }
//        if (failureNum > 0) {
//            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
//            throw new ServiceException(failureMsg.toString());
//        } else {
//            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
//        }
////        ExcelUtil<YwQuestionVO> util = new ExcelUtil<YwQuestionVO>(YwQuestionVO.class);
////        List<YwQuestionVO> list = util.importExcel(file.getInputStream());
////        String operName = getUsername();
////        String message = ywQuestionService.importQuestion(list, updateSupport, operName);
//        return success(successMsg.toString());
//    }
//
//    /**
//     * 获取题库题干详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('question:question:query')")
//    @GetMapping(value = "/{questionId}")
//    public AjaxResult getInfo(@PathVariable("questionId") Long questionId) {
//        return success(ywQuestionService.selectYwQuestionByQuestionId(questionId));
//    }
//
//    /**
//     * 新增题库题干
//     */
//    @PreAuthorize("@ss.hasPermi('question:question:add')")
//    @Log(title = "题库题干", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody YwQuestion ywQuestion) {
//        return toAjax(ywQuestionService.insertYwQuestion(ywQuestion));
//    }
//
//    /**
//     * 修改题库题干
//     */
//    @PreAuthorize("@ss.hasPermi('question:question:edit')")
//    @Log(title = "题库题干", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody YwQuestion ywQuestion) {
//        return toAjax(ywQuestionService.updateYwQuestion(ywQuestion));
//    }
//
//    /**
//     * 删除题库题干
//     */
//    @PreAuthorize("@ss.hasPermi('question:question:remove')")
//    @Log(title = "题库题干", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{questionIds}")
//    public AjaxResult remove(@PathVariable Long[] questionIds) {
//        return toAjax(ywQuestionService.deleteYwQuestionByQuestionIds(questionIds));
//    }
}
